#!/usr/bin/env bash
## https://github.com/d12frosted/mirror-elpa
set -ue

emacs_path="/usr/bin/emacs"

mirror_path="$HOME/elpa-mirror-2021-main"
mirror_url="https://gitlab.com/d12frosted/elpa-mirror"

elpa_clone_path="$HOME/.cache/elpa-clone"
elpa_clone_url="https://gitee.com/blindingdark/elpa-clone.git"

function log {
  echo "[$(date '+%d/%m/%y %H:%M:%S')]" "$@"
}

function clone {
  log "Updating mirror for $2 ($1)"
  $emacs_path -l "$elpa_clone_path/elpa-clone.el" -nw --batch --eval="(elpa-clone \"$1\" \"$mirror_path/$2\")"
}

if [[ "$mirror_path" = "" ]]; then
  mirror_path="$(mktemp -d)"
fi

trap '[ "$?" -eq 0 ] || log Error! Could not update elpa mirrors!' EXIT

log "Start updating elpa mirrors"
log "mirror_path: $mirror_path"
log "elpa_clone_path: $elpa_clone_path"
log "PATH: $PATH"

if [[ ! -d $elpa_clone_path ]]; then
  log "elpa-clone tool is missing, installing it..."
  git clone --depth 1 "$elpa_clone_url" "$elpa_clone_path"
else
  log "updating elpa-clone"
  (
    cd "$elpa_clone_path"
    git fetch origin
    git reset --hard origin/master
  )
fi

if [[ ! -d "$mirror_path" ]]; then
  log "cloning mirror repository"
  git clone --depth 1 "$mirror_url" "$mirror_path"
fi

clone "https://orgmode.org/elpa/" "org"
clone "https://elpa.gnu.org/packages/" "gnu"
clone "https://melpa.org/packages/" "melpa"
clone "https://stable.melpa.org/packages/" "melpa-stable"

log "Done updating elpa mirrors"
